package com.an.springresource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;

public class FileSourceExample {

  public static void main(String[] args) throws IOException {
    String filePath = "D:\\personal\\workspace\\eclipse_oxygen_work_bas\\spring-boot-learn\\src\\main\\java\\com\\an\\springresource\\text.txt";
    
    // 使用系统文件路径方式加载
    WritableResource resource = new PathResource(filePath);
    
    // 使用类路径加载文件
    Resource resource2 = new ClassPathResource("/com/an/springresource/text.txt");
    
    // 使用WritableResource写资源文件
    OutputStream outputStream = resource.getOutputStream();
    outputStream.write("人民".getBytes());
    outputStream.close();
    
    // 使用resource读取资源文件
    InputStream inputStream = resource.getInputStream();
    InputStream inputStream2 = resource2.getInputStream();
    
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    int i;
    while((i = inputStream.read()) != -1) {
      arrayOutputStream.write(i);
    }
    
    System.err.println(arrayOutputStream.toString());
    
    // 创建文件
    resource.createRelative("sss.csv");
    
    System.out.println(resource.getFilename());
    System.out.println(resource2.getFilename());
  }
}

